<template>
	<div class="image-upload">
		<el-upload
			class="upload-container"
			:action="uploadConfig.apiObj.url"
			:show-file-list="false"
			:on-success="handleUploadSuccess"
			:on-error="handleUploadError"
			:before-upload="beforeUpload"
			:data="uploadData"
			:headers="uploadHeaders">
			<div v-if="imageUrl" class="image-preview-container" :style="imageStyle">
				<img :src="imageUrl" class="upload-image" :style="imageStyle" />
				<div class="image-overlay">
					<div class="overlay-actions">
						<el-icon class="action-icon" @click.stop="handleDelete" style="font-size: 30px">
							<Delete />
						</el-icon>
					</div>
				</div>
			</div>
			<div v-else class="upload-placeholder" :style="placeholderStyle">
				<el-icon><Plus /></el-icon>
				<div class="upload-text">{{ placeholder }}</div>
			</div>
		</el-upload>
		<div v-if="tip" class="upload-tip">{{ tip }}</div>
	</div>
</template>

<script>
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import uploadConfig from '@/config/upload.js'
import tool from '@/utils/tool'

export default {
	name: 'ImageUpload',
	components: {
		Plus,
		Edit,
		Delete
	},
	props: {
		// 图片地址 v-model绑定
		modelValue: {
			type: String,
			default: ''
		},
		// 上传容器的宽度
		width: {
			type: [String, Number],
			default: 120
		},
		// 上传容器的高度
		height: {
			type: [String, Number],
			default: 120
		},
		// 占位符文字
		placeholder: {
			type: String,
			default: '上传图片'
		},
		// 提示文字
		tip: {
			type: String,
			default: '支持 JPG、PNG、GIF 格式，大小不超过10MB'
		},
		// 支持的文件类型
		accept: {
			type: Array,
			default: () => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
		},
		// 文件大小限制（MB）
		maxSize: {
			type: Number,
			default: 10
		},
		// 是否禁用
		disabled: {
			type: Boolean,
			default: false
		}
	},
	emits: ['update:modelValue', 'success', 'error', 'delete'],
	data() {
		return {
			uploadConfig: uploadConfig
		}
	},
	computed: {
		// 当前图片地址
		imageUrl() {
			return this.modelValue;
		},
		// 图片样式
		imageStyle() {
			return {
				width: this.formatSize(this.width),
				height: this.formatSize(this.height)
			};
		},
		// 占位符样式
		placeholderStyle() {
			return {
				width: this.formatSize(this.width),
				height: this.formatSize(this.height)
			};
		},
		// 上传数据
		uploadData() {
			return {};
		},
		// 上传请求头
		uploadHeaders() {
			let token = tool.data.get("TOKEN");
			return token ? {
				'Authorization': `Bearer ${token}`
			} : {};
		}
	},
	methods: {
		// 格式化尺寸
		formatSize(size) {
			if (typeof size === 'number') {
				return size + 'px';
			}
			return size;
		},
		// 上传前验证
		beforeUpload(file) {
			if (this.disabled) {
				this.$message.error('上传功能已禁用');
				return false;
			}

			const isValidType = this.accept.includes(file.type);
			const isLtMaxSize = file.size / 1024 / 1024 < this.maxSize;

			if (!isValidType) {
				const acceptTypes = this.accept.map(type =>
					type.replace('image/', '').toUpperCase()
				).join('/');
				this.$message.error(`上传图片只能是 ${acceptTypes} 格式!`);
				return false;
			}
			if (!isLtMaxSize) {
				this.$message.error(`上传图片大小不能超过 ${this.maxSize}MB!`);
				return false;
			}
			return true;
		},
		// 上传成功回调
		handleUploadSuccess(response) {
			if (response.code === 0) {
				this.$emit('update:modelValue', response.data.src);
				this.$emit('success', response.data);
				this.$message.success('上传成功');
			} else {
				this.$emit('error', response);
				this.$message.error(response.msg || '上传失败');
			}
		},
		// 上传失败回调
		handleUploadError(error) {
			console.error('上传失败:', error);
			this.$emit('error', error);
			this.$message.error('上传失败，请重试');
		},
		// 删除图片
		handleDelete() {
			this.$confirm('确定要删除这张图片吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$emit('update:modelValue', '');
				this.$emit('delete');
				this.$message.success('已删除图片');
			}).catch(() => {
				// 用户取消删除
			});
		},
	}
}
</script>

<style scoped>
.image-upload {
	display: inline-block;
}

.upload-container {
	display: inline-block;
}

.upload-placeholder {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	transition: border-color 0.3s;
	background-color: #fafafa;
}

.upload-placeholder:hover {
	border-color: #409eff;
	color: #409eff;
}

.upload-image {
	object-fit: cover;
	border-radius: 6px;
	border: 1px solid #d9d9d9;
	cursor: pointer;
	display: block;
}

.image-preview-container {
	position: relative;
	display: inline-block;
	border-radius: 6px;
	overflow: hidden;
}

.image-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	opacity: 0;
	transition: opacity 0.3s;
	cursor: pointer;
}

.image-preview-container:hover .image-overlay {
	opacity: 1;
}

.overlay-actions {
	display: flex;
	gap: 10px;
}

.action-icon {
	color: white;
	font-size: 18px;
	cursor: pointer;
	padding: 6px;
	border-radius: 4px;
	transition: background-color 0.3s;
}

.action-icon:hover {
	background-color: rgba(255, 255, 255, 0.2);
}

.upload-text {
	font-size: 12px;
	color: #8c939d;
	margin-top: 5px;
}

.upload-tip {
	font-size: 12px;
	color: #8c939d;
	margin-top: 5px;
	line-height: 1.4;
}

/* 禁用状态 */
.upload-container.is-disabled .upload-placeholder {
	cursor: not-allowed;
	background-color: #f5f7fa;
	border-color: #e4e7ed;
	color: #c0c4cc;
}

.upload-container.is-disabled .upload-image {
	cursor: not-allowed;
	opacity: 0.6;
}
</style>
